package org.dppc.fine4j.proxychain.support;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import org.dppc.fine4j.proxychain.MethodCommand;
import org.dppc.fine4j.proxychain.MethodProxyChain;

/**
 * JDK 动态代理 实现ProxyHandler
 * 
 * @author maomh
 */
public class JDKProxyHandler extends AbstractProxyHandler implements InvocationHandler {
	// JDK动态代理 代理接口
	private Class<?>[] interfaces;
	
	
	/**
	 * 构造函数
	 * 
	 * @param interfaces
	 */
	public JDKProxyHandler(Class<?>[] interfaces) {
		if (interfaces == null || interfaces.length == 0) {
			throw new RuntimeException("必须指定要实现动态代理的接口！");
		}
		this.interfaces =interfaces;
	}
	
	
	@Override
	protected boolean checkType(Object object) {
		boolean pass =false;
		for (Class<?> intfClass : interfaces) {
			if (intfClass.isInstance(object)) {
				pass =true;
				break;
			}
		}
		return pass;
	}
	
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		MethodCommand command =new MethodCommand(getProxy(), getTarget(), method, args);
		MethodProxyChain chain =new MethodProxyChain(this.methodProxies);
		return chain.doInvoke(command);
	}

}
